import express from 'express';
import { authenticateToken } from '../middleware/auth';
import { getDatabase } from '../database/init';

const router = express.Router();

// 使用认证中间件保护所有通知路由
router.use(authenticateToken);

// 获取用户的通知设置
router.get('/settings', async (req, res) => {
  try {
    const userId = req.userId;
    const db = getDatabase();
    
    const result = await db.query(
      'SELECT * FROM notification_settings WHERE user_id = $1',
      [userId]
    );

    if (result.rows.length === 0) {
      // 如果没有设置，返回默认设置
      const defaultSettings = {
        user_id: userId,
        task_reminders: true,
        daily_summary: true,
        weekly_review: true,
        overdue_alerts: true,
        reminder_time: '09:00',
        sound_enabled: true,
        vibration_enabled: true,
        email_notifications: false,
        created_at: new Date(),
        updated_at: new Date()
      };
      
      // 插入默认设置
      await db.query(`
        INSERT INTO notification_settings 
        (user_id, task_reminders, daily_summary, weekly_review, overdue_alerts, 
         reminder_time, sound_enabled, vibration_enabled, email_notifications)
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
      `, [
        userId, 
        defaultSettings.task_reminders,
        defaultSettings.daily_summary,
        defaultSettings.weekly_review,
        defaultSettings.overdue_alerts,
        defaultSettings.reminder_time,
        defaultSettings.sound_enabled,
        defaultSettings.vibration_enabled,
        defaultSettings.email_notifications
      ]);

      res.json(defaultSettings);
    } else {
      res.json(result.rows[0]);
    }
  } catch (error) {
    console.error('获取通知设置失败:', error);
    res.status(500).json({ error: '获取通知设置失败' });
  }
});

// 更新用户的通知设置
router.put('/settings', async (req, res) => {
  try {
    const userId = req.userId;
    const db = getDatabase();
    
    // 首先获取现有设置
    const existingResult = await db.query(
      'SELECT * FROM notification_settings WHERE user_id = $1',
      [userId]
    );
    
    let currentSettings;
    if (existingResult.rows.length === 0) {
      // 如果没有现有设置，创建默认设置
      const defaultSettings = {
        task_reminders: true,
        daily_summary: true,
        weekly_review: true,
        overdue_alerts: true,
        reminder_time: '09:00',
        sound_enabled: true,
        vibration_enabled: true,
        email_notifications: false
      };
      
      const insertResult = await db.query(`
        INSERT INTO notification_settings 
        (user_id, task_reminders, daily_summary, weekly_review, overdue_alerts, 
         reminder_time, sound_enabled, vibration_enabled, email_notifications)
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
        RETURNING *
      `, [
        userId,
        defaultSettings.task_reminders,
        defaultSettings.daily_summary,
        defaultSettings.weekly_review,
        defaultSettings.overdue_alerts,
        defaultSettings.reminder_time,
        defaultSettings.sound_enabled,
        defaultSettings.vibration_enabled,
        defaultSettings.email_notifications
      ]);
      
      currentSettings = insertResult.rows[0];
    } else {
      currentSettings = existingResult.rows[0];
    }
    
    // 合并现有设置和新设置（只更新提供的字段）
    const updatedSettings = {
      task_reminders: req.body.task_reminders !== undefined ? req.body.task_reminders : currentSettings.task_reminders,
      daily_summary: req.body.daily_summary !== undefined ? req.body.daily_summary : currentSettings.daily_summary,
      weekly_review: req.body.weekly_review !== undefined ? req.body.weekly_review : currentSettings.weekly_review,
      overdue_alerts: req.body.overdue_alerts !== undefined ? req.body.overdue_alerts : currentSettings.overdue_alerts,
      reminder_time: req.body.reminder_time !== undefined ? req.body.reminder_time : currentSettings.reminder_time,
      sound_enabled: req.body.sound_enabled !== undefined ? req.body.sound_enabled : currentSettings.sound_enabled,
      vibration_enabled: req.body.vibration_enabled !== undefined ? req.body.vibration_enabled : currentSettings.vibration_enabled,
      email_notifications: req.body.email_notifications !== undefined ? req.body.email_notifications : currentSettings.email_notifications
    };

    // 更新设置
    const result = await db.query(`
      UPDATE notification_settings 
      SET task_reminders = $2, daily_summary = $3, weekly_review = $4, 
          overdue_alerts = $5, reminder_time = $6, sound_enabled = $7, 
          vibration_enabled = $8, email_notifications = $9, updated_at = NOW()
      WHERE user_id = $1
      RETURNING *
    `, [
      userId,
      updatedSettings.task_reminders,
      updatedSettings.daily_summary,
      updatedSettings.weekly_review,
      updatedSettings.overdue_alerts,
      updatedSettings.reminder_time,
      updatedSettings.sound_enabled,
      updatedSettings.vibration_enabled,
      updatedSettings.email_notifications
    ]);

    res.json(result.rows[0]);
  } catch (error) {
    console.error('更新通知设置失败:', error);
    res.status(500).json({ error: '更新通知设置失败' });
  }
});

// 检查需要发送的提醒
router.post('/check-reminders', async (req, res) => {
  try {
    const userId = req.userId;
    const db = getDatabase();
    const now = new Date();

    // 获取用户的通知设置
    const settingsResult = await db.query(
      'SELECT * FROM notification_settings WHERE user_id = $1',
      [userId]
    );

    if (settingsResult.rows.length === 0 || !settingsResult.rows[0].task_reminders) {
      return res.json([]);
    }

    // 查找需要提醒的任务（使用每个任务的个性化提醒间隔）
    const currentTime = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
    
    const tasksResult = await db.query(`
      SELECT id, title, description, due_date, priority, category, reminder_minutes
      FROM tasks 
      WHERE user_id = $1 
        AND due_date IS NOT NULL
        AND status != 'done'
        AND due_date > $2
      ORDER BY due_date ASC
    `, [userId, currentTime]);

    const reminders = [];
    
    for (const task of tasksResult.rows) {
      try {
        // 安全的日期处理
        if (!task.due_date) continue;
        
        const dueDate = new Date(task.due_date);
        if (isNaN(dueDate.getTime())) {
          console.warn(`无效的due_date: ${task.due_date}, 任务ID: ${task.id}`);
          continue;
        }
        
        const reminderMinutes = task.reminder_minutes || 30; // 默认30分钟
        const reminderTime = new Date(dueDate.getTime() - (reminderMinutes * 60 * 1000));
        
        // 检查是否应该发送提醒（提醒时间已到但还未过期）
        if (reminderTime <= now && dueDate > now) {
          reminders.push({
            taskId: task.id,
            title: task.title,
            message: `任务"${task.title}"将在${reminderMinutes}分钟后到期`,
            type: 'reminder',
            priority: task.priority,
            category: task.category,
            dueDate: task.due_date,
            reminderMinutes: reminderMinutes
          });
        }
      } catch (taskError) {
        console.error(`处理任务提醒时出错 (任务ID: ${task.id}):`, taskError);
        continue;
      }
    }

    res.json(reminders);
  } catch (error) {
    console.error('检查提醒失败:', error);
    res.status(500).json({ error: '检查提醒失败' });
  }
});

// 获取逾期任务
router.get('/overdue-tasks', async (req, res) => {
  try {
    const userId = req.userId;
    const db = getDatabase();
    const now = new Date();

    // 获取用户的通知设置
    const settingsResult = await db.query(
      'SELECT * FROM notification_settings WHERE user_id = $1',
      [userId]
    );

    if (settingsResult.rows.length === 0 || !settingsResult.rows[0].overdue_alerts) {
      return res.json([]);
    }

    // 查找逾期任务
    const currentTime = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
    
    const tasksResult = await db.query(`
      SELECT id, title, description, due_date, priority, category
      FROM tasks 
      WHERE user_id = $1 
        AND due_date IS NOT NULL
        AND due_date < $2
        AND status != 'done'
      ORDER BY due_date ASC
    `, [userId, currentTime]);

    const overdueTasks = tasksResult.rows.map(task => ({
      id: task.id,
      title: task.title,
      description: task.description,
      dueDate: task.due_date,
      priority: task.priority,
      category: task.category,
      overdueDays: Math.ceil((now.getTime() - new Date(task.due_date).getTime()) / (1000 * 60 * 60 * 24))
    }));

    res.json(overdueTasks);
  } catch (error) {
    console.error('获取逾期任务失败:', error);
    res.status(500).json({ error: '获取逾期任务失败' });
  }
});

// 获取每日总结数据
router.get('/daily-summary', async (req, res) => {
  try {
    const userId = req.userId;
    const db = getDatabase();
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    // 获取用户的通知设置
    const settingsResult = await db.query(
      'SELECT * FROM notification_settings WHERE user_id = $1',
      [userId]
    );

    if (settingsResult.rows.length === 0 || !settingsResult.rows[0].daily_summary) {
      return res.json(null);
    }

    // 获取今日完成的任务数
    const completedResult = await db.query(`
      SELECT COUNT(*) as count
      FROM tasks 
      WHERE user_id = $1 
        AND status = 'done'
        AND updated_at >= $2 AND updated_at < $3
    `, [userId, today, tomorrow]);

    // 获取待办任务数
    const pendingResult = await db.query(`
      SELECT COUNT(*) as count
      FROM tasks 
      WHERE user_id = $1 
        AND status != 'done'
    `, [userId]);

    // 获取逾期任务数
    const currentTime = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
    
    const overdueResult = await db.query(`
      SELECT COUNT(*) as count
      FROM tasks 
      WHERE user_id = $1 
        AND status != 'done'
        AND due_date IS NOT NULL
        AND due_date < $2
    `, [userId, currentTime]);

    // 获取即将到期的任务数（未来3天内）
    const upcomingDeadline = new Date();
    upcomingDeadline.setDate(upcomingDeadline.getDate() + 3);
    const upcomingDeadlineStr = upcomingDeadline.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
    
    const upcomingResult = await db.query(`
      SELECT COUNT(*) as count
      FROM tasks 
      WHERE user_id = $1 
        AND status != 'done'
        AND due_date IS NOT NULL
        AND due_date BETWEEN $2 AND $3
    `, [userId, currentTime, upcomingDeadlineStr]);

    const summary = {
      date: today,
      completed: parseInt(completedResult.rows[0].count),
      pending: parseInt(pendingResult.rows[0].count),
      overdue: parseInt(overdueResult.rows[0].count),
      upcomingDeadlines: parseInt(upcomingResult.rows[0].count)
    };

    res.json(summary);
  } catch (error) {
    console.error('获取每日总结失败:', error);
    res.status(500).json({ error: '获取每日总结失败' });
  }
});

// 记录通知发送历史
router.post('/history', async (req, res) => {
  try {
    const userId = req.userId;
    const db = getDatabase();
    const { type, title, message, task_id, sent_at } = req.body;

    const result = await db.query(`
      INSERT INTO notification_history 
      (user_id, type, title, message, task_id, sent_at)
      VALUES ($1, $2, $3, $4, $5, $6)
      RETURNING *
    `, [userId, type, title, message, task_id, sent_at || new Date()]);

    res.json(result.rows[0]);
  } catch (error) {
    console.error('记录通知历史失败:', error);
    res.status(500).json({ error: '记录通知历史失败' });
  }
});

// 获取通知历史
router.get('/history', async (req, res) => {
  try {
    const userId = req.userId;
    const db = getDatabase();
    const { limit = 50, offset = 0, type } = req.query;

    let query = `
      SELECT * FROM notification_history 
      WHERE user_id = $1
    `;
    const params = [userId];

    if (type) {
      query += ` AND type = $${params.length + 1}`;
      params.push(type as string);
    }

    query += ` ORDER BY sent_at DESC LIMIT $${params.length + 1} OFFSET $${params.length + 2}`;
    params.push(limit as string, offset as string);

    const result = await db.query(query, params);
    res.json(result.rows);
  } catch (error) {
    console.error('获取通知历史失败:', error);
    res.status(500).json({ error: '获取通知历史失败' });
  }
});

// 标记通知为已读
router.patch('/history/:id/read', async (req, res) => {
  try {
    const userId = req.userId;
    const db = getDatabase();
    const { id } = req.params;

    const result = await db.query(`
      UPDATE notification_history 
      SET is_read = true, read_at = NOW()
      WHERE id = $1 AND user_id = $2
      RETURNING *
    `, [id, userId]);

    if (result.rows.length === 0) {
      return res.status(404).json({ error: '通知记录不存在' });
    }

    res.json(result.rows[0]);
  } catch (error) {
    console.error('标记通知为已读失败:', error);
    res.status(500).json({ error: '标记通知为已读失败' });
  }
});

// 清理旧的通知历史（保留最近30天）
router.delete('/history/cleanup', async (req, res) => {
  try {
    const userId = req.userId;
    const db = getDatabase();
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const result = await db.query(`
      DELETE FROM notification_history 
      WHERE user_id = $1 AND sent_at < $2
    `, [userId, thirtyDaysAgo]);

    res.json({ 
      message: '清理完成', 
      deletedCount: result.rowCount 
    });
  } catch (error) {
    console.error('清理通知历史失败:', error);
    res.status(500).json({ error: '清理通知历史失败' });
  }
});

export default router;
